/**
 * xaseTabs Extension – History
 * ************************************************************************************************************** 
 * Saves tab-state in URL for history and bookmark functionality
 * Requires jQuery Address Plugin: http://www.asual.com/jquery/address/
 *                                     
 * Version: 		0.2.0
 * Documentation:	http://xasetabs.noelboss.ch/
 * Download:		http://code.google.com/p/xasetabs
 * Source:			svn checkout http://xasetabs.googlecode.com/svn/trunk/ xasetabs-read-only
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * © 2010 by Noël Bossart                                 
 */
; var xaseTabsExtensions = xaseTabsExtensions || {};
(function($) {
	xaseTabsExtensions.history = function(customEvents) {
		var historyExtensionInit = false; // internal state var
		
		customEvents.setupTabs.unshift(function(options) {
			this.bind("setupTabs." + options.namespace, function(e, selected) {
				if (e.isDefaultPrevented() || e.isPropagationStopped()) {
					return;
				}

				var $t = $(this),
					$tabs = $t.data('$tabs'),
					init = function(event) {
						historyExtensionInit = true; 
						var act = unescape(event.parameters[options.namespace]),
						 	$act = $tabs.filter(':contains('+act+')');
						if(act){                                            
							$act.addClass(options.activeClass);
						}
					},
					externalChange = function(event) {
						var act = unescape(event.parameters[options.namespace]);
						if(act){
							$tabs.filter(':contains('+act+')').click();
						} else {
							$tabs.eq(0).click(); 
						}
					};           
					
				$.address.init(init);
				$.address.externalChange(externalChange);
			});
		});
		customEvents.activate.unshift(function(options) {
			this.bind("activate." + options.namespace, function(e, selected) {
				if (e.isDefaultPrevented() || e.isPropagationStopped()) {
					return;
				}
				var act = $.trim($(selected).text());
				var $t = $(this);
				
				if(historyExtensionInit){
					$.address.parameter(options.namespace, act);
				}
			});
		});
		return customEvents;
	};
})(jQuery);